package com.czy.owner.ui.archive;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.api.CarParameterSetApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.entity.InsuranceCompanyEntity;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.PhoneUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

import butterknife.BindView;

/**
 * Created by King on 2017-05-17
 * 车险提醒
 */

public class InsuranceSettingActivity extends BaseActivity {
    @BindView(R.id.tv_insurance_name)
    TextView tvName;
    @BindView(R.id.tv_insurance_expiry)
    TextView tvExpiry;
    @BindView(R.id.btn_insurance_submit)
    Button btnSubmit;

    private int currentYear, currentMonth, currentDay;
    private CarInfo mCarInfo;
    private InsuranceCompanyEntity insuranceCompanyEntity;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_insurance_setting;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText("车险提醒");
        getSubTitle().setVisibility(View.GONE);
        if (getIntent().getExtras() == null || (mCarInfo = (CarInfo) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(this, "参数异常!");
            finish();
            return;
        }
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR) + 10;
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
        if(mCarInfo.getInsuranceId() > 0){
            tvName.setText(mCarInfo.getInsuranceName());
            btnSubmit.setEnabled(true);
        }
        tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(InsuranceSettingActivity.this,InsuranceCompanyActivity.class).putExtra(Constants.TRANSMISSION_CONTENT_KEY,mCarInfo),1);
            }
        });
        if (mCarInfo.getNextInsuranceTime() == 0) {
            tvExpiry.setText("");
        } else {
            Date date = new Date(mCarInfo.getNextInsuranceTime());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            tvExpiry.setText("" + format.format(date));
        }
        tvExpiry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateDialog();
            }
        });

        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(insuranceCompanyEntity == null && mCarInfo.getInsuranceId() == 0){
                    PhoneUtils.ShowToastMessage(InsuranceSettingActivity.this, "请选择保险公司!");
                    return;
                }

                if (TextUtils.isEmpty(tvExpiry.getText().toString().trim())) {
                    PhoneUtils.ShowToastMessage(InsuranceSettingActivity.this, "请选择保险到期日期!");
                    showDateDialog();
                    return;
                }

                CarParameterSetApi carParameterSetApi = new CarParameterSetApi(new HttpOnNextListener<String>() {
                    @Override
                    public void onNext(String o) {
                        Toast.makeText(InsuranceSettingActivity.this, "车险信息设置成功!", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        Toast.makeText(InsuranceSettingActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                },InsuranceSettingActivity.this);



                HashMap<String,Object> requestMap = new HashMap<>();
                requestMap.put("session", UserHelper.getInstance().getSession(InsuranceSettingActivity.this));
                requestMap.put("ownerCarId",mCarInfo.getOwnerCarId());
                requestMap.put("insuranceId","" + (insuranceCompanyEntity == null?mCarInfo.getInsuranceId():insuranceCompanyEntity.getInsuranceId()));
                DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                Date date = null;
                try {
                    date  = format1.parse(tvExpiry.getText().toString().trim());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                requestMap.put("nextInsuranceTime","" + date.getTime());

                carParameterSetApi.setMap(requestMap);
                HttpManager.getInstance().doHttpDeal(carParameterSetApi);
            }
        });
    }

    @Override
    protected void updateViews() {

    }
    private void showDateDialog() {
        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
        if (!TextUtils.isEmpty(tvExpiry.getText())) {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = formatter.parse(tvExpiry.getText().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(date !=null){
                tmpCalendar.setTime(date);
            }
        }
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        final Dialog mDateDialog = new Dialog(InsuranceSettingActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(InsuranceSettingActivity.this).inflate(R.layout.dialog_archive_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.tv_archive_add_title);
        tvTitle.setText("请选择时间");
        final WheelView wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        final WheelView wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        final WheelView wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);


        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(InsuranceSettingActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<String>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(InsuranceSettingActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);
        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""),
                        txtMonth = "0" + (wvMonth.getCurrentItem() + 1),
                        txtDay = "0" + (wvDay.getCurrentItem() + 1);
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);
                tvExpiry.setText(txtYear + "-" + txtMonth + "-" + txtDay);
                mDateDialog.dismiss();
            }
        });

        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }

    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 1){
            insuranceCompanyEntity = (InsuranceCompanyEntity)data.getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY);
            tvName.setText(insuranceCompanyEntity.getInsuranceName());
            btnSubmit.setEnabled(true);
        }
    }
}
